// 性能监控器 - 监控应用性能
export class PerformanceMonitor {
  constructor() {
    this.metrics = {
      frameCount: 0,
      lastTime: performance.now(),
      fps: 0,
      frameTime: 0,
      memoryUsage: 0
    }
    
    this.isMonitoring = false
    this.callbacks = []
  }

  start() {
    this.isMonitoring = true
    this.update()
  }

  stop() {
    this.isMonitoring = false
  }

  update() {
    if (!this.isMonitoring) return

    const currentTime = performance.now()
    const deltaTime = currentTime - this.metrics.lastTime
    
    this.metrics.frameCount++
    this.metrics.frameTime = deltaTime
    
    // 每秒更新一次FPS
    if (deltaTime >= 1000) {
      this.metrics.fps = Math.round((this.metrics.frameCount * 1000) / deltaTime)
      this.metrics.frameCount = 0
      this.metrics.lastTime = currentTime
      
      // 获取内存使用情况（如果支持）
      if (performance.memory) {
        this.metrics.memoryUsage = Math.round(performance.memory.usedJSHeapSize / 1048576) // MB
      }
      
      // 通知回调函数
      this.callbacks.forEach(callback => callback(this.metrics))
    }
    
    requestAnimationFrame(() => this.update())
  }

  onUpdate(callback) {
    this.callbacks.push(callback)
  }

  getMetrics() {
    return { ...this.metrics }
  }

  // 测量函数执行时间
  static measure(name, fn) {
    const start = performance.now()
    const result = fn()
    const end = performance.now()
    
    console.log(`${name} 执行时间: ${(end - start).toFixed(2)}ms`)
    return result
  }

  // 测量异步函数执行时间
  static async measureAsync(name, fn) {
    const start = performance.now()
    const result = await fn()
    const end = performance.now()
    
    console.log(`${name} 执行时间: ${(end - start).toFixed(2)}ms`)
    return result
  }
}